package project1;


public class RegisterCommand extends ICommand {
	private byte[] serviceIp;
	private int servicePort;
	private long serviceData;
	private String serviceName;

	protected RegisterCommand(byte seqNumber, int type) {
		super(seqNumber, type);
		this.servicePort = -1;
		this.serviceData = -1;
	}

	@Override
	public byte[] generateMessage() {
		if (serviceIp == null || servicePort == -1 || serviceData == -1 || serviceName == null) 
			throw new IllegalStateException("Please set the serviceip, port, data, namelength and name before calling generate messages.");
		
		byte[] serviceNameTemp = serviceName.getBytes();
		// generate the header information
		byte[] ret = Util.generateHeader(seqNumber, type, 15 + serviceNameTemp.length);
		
		// Add the ip address
		for (int i = 0; i < 4; i++) {
			ret[4 + i] = serviceIp[i];
		}
		
		// Add the port number
		ret[8] = (byte) ((servicePort >> 8) & 0xFF);
		ret[9] = (byte) (servicePort & 0xFF);
		
		// Add the service data
		ret[10] = (byte) ((serviceData >> 24) & 0xFF);
		ret[11] = (byte) ((serviceData >> 16) & 0xFF);
		ret[12] = (byte) ((serviceData >> 8) & 0xFF);
		ret[13] = (byte) (serviceData & 0xFF);
		
		// Add the service name length
		ret[14] = (byte) (serviceNameTemp.length & 0xFF);
		
		// Add the service name
		for (int i = 0; i < serviceNameTemp.length; i++) {
			ret[15 + i] = serviceNameTemp[i];
		}
		
		return ret;
	}

	public void setServiceIp(byte[] ip) {
		this.serviceIp = ip;
	}
	
	public void setServicePort(int port) {
		this.servicePort = port;
	}
	
	public void setServiceData(long data) {
		this.serviceData = data;
	}
	
	public void setServiceName(String name) {
		this.serviceName = name;
	}
	
	public byte[] getServiceIp() {
		return this.serviceIp;
	}
	
	public int getPort() {
		return this.servicePort;
	}
	
	public long getServiceData() {
		return this.serviceData;
	}
	
	public String getServiceName() {
		return this.serviceName;
	}
}
